package controllers.api;

import java.io.IOException;
import java.lang.reflect.Type;
import javax.inject.Inject;
import com.google.gson.reflect.TypeToken;
import controllers.Data;
import play.mvc.Controller;
import services.image.ImageSearchService;
import services.image.ImageSearchService.ImageExt;
import services.video.VideoFeed;
import services.video.View;
import services.video.YouTubeClient;
import services.video.YouTubeUrl;
import play.mvc.Http.StatusCode;

public class Internet extends MeApi {
	
	public enum SearchType {
		IMAGES,VIDEOS;
	}
	
	@Inject
	static ImageSearchService imageSearchService;
	
	public static void search(String q, 
			String type, Integer offset, Integer limit) throws IOException {
		if(type==null) {
			flash.put("message", "Es necesario especificar el parámetro type.");
			error(StatusCode.BAD_REQUEST, "Es necesario especificar el parámetro type.");
		}
		if(offset == null) offset = 1;
		if(limit==null || limit > 8 || limit==0) {
			limit = 8;
		}
		if(SearchType.IMAGES.name().equals(type.toUpperCase())) {
			Type dataType = new TypeToken<Data<ImageExt>>(){}.getType();
			//renderJSON(imageSearchService.search(q, offset, limit), dataType);
			Data<ImageExt> data = imageSearchService.search(q, offset, limit);
			renderTemplate("api/internet/images.json", data);
		} else if(SearchType.VIDEOS.name().equals(type.toUpperCase())) {
			YouTubeClient client = new YouTubeClient();
			View.header("Get Videos");
			// build URL for the video feed for "search stories"
		    YouTubeUrl url = YouTubeUrl.forVideosFeed();
		    url.q = q;
		    url.maxResults = limit;
		    //Youtube api's offset starts at 1.
		    offset++;
		    url.startIndex = offset;
		    // execute GData request for the feed
		    VideoFeed data = client.executeGetVideoFeed(url);
		    Type dataType = new TypeToken<VideoFeed>(){}.getType();
		    //renderJSON(feed, dataType);
		    renderTemplate("api/internet/videos.json", data);
		} else {
			String message = "El parámetro type debe tener uno de los siguientes valores: ";
			for(SearchType searchType : SearchType.values()) {
				message += searchType.name() + ",";
			}
			flash.put("message", message);
			error(StatusCode.BAD_REQUEST, message);
		}
		
	}
	
}